﻿using Authority.Model;
using Common.Library;
using Dapper.Library;
using Dapper.MsSql.Library;
using Document.Library;
using Encrypt.Library;
using Dapper.Library.DataAccessSql;
using Redis.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using Tool.Model;
using Network.Library;
using Message.Library.Aliyun;
using Container.Library;

namespace Authority.Logic
{
    /// <summary>
    /// 管理员操作逻辑类
    /// </summary>
    public class SysUserServiceImpl : ISysUserService
    {
        #region 用户登录

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ResultFileContent LoadValidateCode()
        {
            var resultInfo = new ResultFileContent();
            string code = ValidateCode.CreateValidateCode(4);
            string md5 = SecurityHelper.GetMD5Hash(HttpHelper.GetIP());

            RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                .StringSet(ConstRedisKey.RedisValidateCode + md5, code, ConstRedisKey.TimeOut);

            byte[] bytes = ValidateCode.CreateValidateGraphic(code);
            if (bytes.Length > 0)
            {
                resultInfo.Success = true;
                resultInfo.fileContents = bytes;
                resultInfo.contentType = @"image/jpeg";
            }
            return resultInfo;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<SysUserInfo> UserLogin(LoginRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<SysUserInfo>();
            //redis获取验证码
            string md5 = SecurityHelper.GetMD5Hash(HttpHelper.GetIP());
            var ValidateCode = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb).StringGet(ConstRedisKey.RedisValidateCode + md5);

            //验证码验证
            if (ValidateCode.IsNotNullOrEmpty())
            {
                if (ValidateCode == inputInfo.VialdCode)
                {
                    if (inputInfo.LoginName != null)
                    {
                        //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
                        using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                        {
                            inputInfo.Password = SecurityHelper.GetMD5Hash(inputInfo.Password);
                            //先查询是否有该账号存在
                            var info = con.QuerySet<View_SysUserEntity>()
                                .AndWhere(p => p.sLoginName == inputInfo.LoginName)
                                .Multiple();

                            if (info != null && info.Count > 0)
                            {
                                //再核对密码是否正确
                                var result = info.Find(p => p.sLoginName == inputInfo.LoginName && p.sPassword == inputInfo.Password);
                                if (result != null)
                                {
                                    if (result.iState == (int)UserState.Normal)
                                    {
                                        var ticket = result.MapTo<SysUserInfo>();
                                        resultInfo.Code = ActionCodes.Success;
                                        resultInfo.Msg = "操作成功";
                                        resultInfo.Data = ticket;
                                    }
                                    else
                                    {
                                        resultInfo.Msg = "用户已被冻结，请与管理员联系！";
                                    }
                                }
                                else
                                {
                                    resultInfo.Msg = "密码错误！";
                                }
                            }
                            else
                            {
                                resultInfo.Msg = "账号不存在！";
                            }
                        }
                    }
                }
                else
                {
                    resultInfo.Msg = "验证码不正确！";
                }
            }
            else
            {
                resultInfo.Msg = "验证码失效，请重新获取！";
            }
            return resultInfo;
        }

        #endregion

        #region 密码重置操作

        /// <summary>
        /// 发送短信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ForgetPswSendMessage(string parameters)
        {
            var resultInfo = new ResultJsonInfo<int>();
            if (parameters.IsNotNullOrEmpty())
            {
                using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                {

                    var result = con.QuerySet<SysUserEntity>()
                             .AndWhere(p => p.sPhone == parameters).Exists();
                    if (result)
                    {
                        Random rd = new Random();
                        string message = rd.Next(10000, 99999).ToString();
                        RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                            .StringSet(ConstRedisKey.RedisForgetPswCode + parameters, message, ConstRedisKey.ForgetPswCodeTimeOut);

                        var messageInfo = new MessageInfo<object>()
                        {
                            Mobile = parameters,
                            TemplateCodeKey = ConstAliyunSms.ForgetPswTemplateKey,
                            Message = new
                            {
                                code = message
                            }
                        };
                        int sendResult = AliyunSendMsg.SendMessage<object>(messageInfo);
                        if (sendResult == 1)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = 1;
                        }
                        else
                        {
                            resultInfo.Msg = "发送失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,账号不存在！";
                    }
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ResetPassword(UserForgetPswRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();

            string validateInfo = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                          .StringGet(ConstRedisKey.RedisForgetPswCode + inputInfo.sLoginName);

            if (validateInfo.IsNotNullOrEmpty())
            {
                if (inputInfo.sValidate == validateInfo)
                {
                    if (inputInfo.sPsw == inputInfo.sConfirmPsw)
                    {
                        using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                        {
                            var userInfo = con.QuerySet<SysUserEntity>()
                                    .AndWhere(p => p.sLoginName == inputInfo.sLoginName)
                                   .WithNoLock().Single();
                            if (userInfo != null)
                            {
                                userInfo.sPassword = SecurityHelper.GetMD5Hash(inputInfo.sPsw);
                                userInfo.sLockScreenPsw = SecurityHelper.GetMD5Hash(inputInfo.sPsw);
                                var resultCount = con.CommandSet<SysUserEntity>().Update(userInfo);
                                if (resultCount > 0)
                                {
                                    resultInfo.Code = ActionCodes.Success;
                                    resultInfo.Msg = "操作成功";
                                    resultInfo.Data = resultCount;
                                }
                                else
                                {
                                    resultInfo.Msg = "操作失败！";
                                }
                            }
                            else
                            {
                                resultInfo.Code = ActionCodes.InvalidOperation;
                                resultInfo.Msg = "账号不存在！";
                            }
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "两次密码不一致！";
                    }
                }
                else
                {
                    resultInfo.Msg = "验证码错误！";
                }
            }
            else
            {
                resultInfo.Msg = "验证码失效，请重新获取！";
            }
            return resultInfo;
        }
        #endregion

        #region 主页个人信息功能
        /// <summary>
        /// 根据登录账号获取信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<SysUserEntity> LoadUserByLoginName(string loginName)
        {

            var resultInfo = new ResultJsonInfo<SysUserEntity>();
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var userInfo = con.QuerySet<SysUserEntity>()
                    .AndWhere(p => p.sLoginName == loginName)
                    .WithNoLock().Single();

                if (userInfo != null)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功";
                    resultInfo.Data = userInfo;
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 上传图片（后期把图片上传统一处理）
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<string> UploadImage(string webRootPath, Dictionary<string, object> inputInfo)
        {
            var result = new ResultJsonInfo<string>();
            var imageBase64 = inputInfo["imageBase64"].ToString();
            var imageType = inputInfo["imageType"].ToString();
            result.Data = ImageHelper.SaveBase64Image(imageBase64, imageType, webRootPath);
            result.Code = ActionCodes.Success;
            return result;
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<SysUserEntity> SaveUserInfo(UserInfoModifyRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<SysUserEntity>();
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var userInfo = con.QuerySet<SysUserEntity>()
                    .AndWhere(p => p.sLoginName == inputInfo.LoginName)
                    .WithNoLock()
                    .Single();

                userInfo.sUserName = inputInfo.UserName;
                userInfo.iSex = inputInfo.Sex;
                userInfo.sPhone = inputInfo.Phone;
                userInfo.sPicUrl = inputInfo.PicUrl;
                var info = con.CommandSet<SysUserEntity>().Update(userInfo);

                //con.QuerySet<SysUserEntity>()
                //    .AndWhere(a => a.sLoginName == inputInfo.LoginName)
                //    .Top(1)
                //    .Select(a =>
                //        new SysUserEntity
                //        {
                //            sUserName = a.sUserName,
                //            iSex = a.iSex,
                //            sPhone = a.sPhone,
                //            sPicUrl = a.sPicUrl
                //        })
                //    .UpdateSelect(a =>
                //        new SysUserEntity
                //        {
                //            sUserName = inputInfo.UserName,
                //            iSex = inputInfo.Sex,
                //            sPhone = inputInfo.Phone,
                //            sPicUrl = inputInfo.PicUrl
                //        });

                if (info > 0)
                {
                    var loginUser = UserSession.GetLoginUser<SysUserInfo>();
                    loginUser.UserName = inputInfo.UserName;
                    loginUser.Sex = inputInfo.Sex;
                    loginUser.Phone = inputInfo.Phone;
                    loginUser.PicUrl = inputInfo.PicUrl;
                    UserSession.AddLoginUser(loginUser);

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功";
                    resultInfo.Data = userInfo;
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 确认用户修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<bool> SaveChangePwd(UserPswModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<bool>();
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                inputInfo.OldPsw = SecurityHelper.GetMD5Hash(inputInfo.OldPsw);

                var userInfo = con.QuerySet<SysUserEntity>()
                        .AndWhere(p => p.gCode == inputInfo.Code && p.sPassword == inputInfo.OldPsw)
                       .WithNoLock().Single();

                if (userInfo != null)
                {
                    userInfo.sPassword = SecurityHelper.GetMD5Hash(inputInfo.NewPsw);

                    var resultCount = con.CommandSet<SysUserEntity>().Update(userInfo);
                    if (resultCount > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功";
                        resultInfo.Data = resultCount > 0;
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "旧密码不正确！";
                }
            }
            return resultInfo;
        }

        #endregion

        #region 用户管理功能

        /// <summary>
        /// 分页获取用户列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<View_SysUserEntity>> LoadSysUserList(ParametersInfo<UserInfoQueryRequest> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<View_SysUserEntity>>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();

            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = con.QuerySet<View_SysUserEntity>().WithNoLock();
                if (inputInfo.parameters.sKeyWords.IsNotNullOrEmpty())
                {
                    result.AndWhere(p => p.sLoginName.Contains(inputInfo.parameters.sKeyWords) || p.sUserName.Contains(inputInfo.parameters.sKeyWords));
                }
                if (inputInfo.parameters.sDepartmentCode.IsNotNullOrEmpty() && inputInfo.parameters.sDepartmentCode != "0AFEDD1F2219CC67638F08D75301EDFC")
                {
                    result.AndWhere(p => p.sDepartmentCodes.Contains(inputInfo.parameters.sDepartmentCode));
                }
                result.AndWhere(p =>p.iOrganizationCode== loginUser.OrganizationCode);

                var listInfo = result.OrderBy(inputInfo.order == "asc" ? OrderByType.Asc : OrderByType.Desc, inputInfo.field)
                    .PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Data.IsNotNull())
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Data.ToList();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> AddInfo(UserAddRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();

            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            {
                var result = 0;
                if (inputInfo.sPassword == inputInfo.sRepeatPassword)
                {
                    var sysUser = inputInfo.MapTo<SysUserEntity>();

                    //添加功能，直接添加
                    con.Transaction(tran =>
                    {
                        sysUser.gCode = GuidHelper.GetGuid();
                        sysUser.iOrganizationCode = loginUser.OrganizationCode;
                        sysUser.sPassword = SecurityHelper.GetMD5Hash(sysUser.sPassword);
                        sysUser.dCreateTime = DateTime.Now;
                        sysUser.bIsSuperAdmin = false;
                        sysUser.sLockScreenPsw = SecurityHelper.GetMD5Hash(sysUser.sPassword);
                        sysUser.iType = (int)UserType.Company;
                        
                        result = tran.CommandSet<SysUserEntity>()
                            .IfNotExists(p => p.sLoginName == sysUser.sLoginName)
                            .Insert(sysUser);

                        if (result > 0)
                        {
                            //插入用户-角色关联信息
                            List<string> sRoleList = inputInfo.sRoleList.Split(',').ToList();
                            SysUserRoleEntity sysUserRole = null;
                            foreach (var item in sRoleList)
                            {
                                sysUserRole = new SysUserRoleEntity();
                                sysUserRole.gCode = GuidHelper.GetGuid();
                                sysUserRole.gUserCode = sysUser.gCode;
                                sysUserRole.gRoleCode = item;
                                tran.CommandSet<SysUserRoleEntity>().Insert(sysUserRole);
                            }

                            //插入部门-角色关联信息
                            List<string> sDepartmentList = inputInfo.sDepartmentList.Split(',').ToList();
                            SysUserDepartmentEntity userDepartment = null;
                            foreach (var item in sDepartmentList)
                            {
                                userDepartment = new SysUserDepartmentEntity();
                                userDepartment.gCode = GuidHelper.GetGuid();
                                userDepartment.gUserCode = sysUser.gCode;
                                userDepartment.gDepartmentCode = item;
                                tran.CommandSet<SysUserDepartmentEntity>().Insert(userDepartment);
                            }

                            //插入岗位-角色关联信息
                            List<string> sPostList = inputInfo.sPostList.Split(',').ToList();
                            SysUserPostEntity userPost = null;
                            foreach (var item in sPostList)
                            {
                                userPost = new SysUserPostEntity();
                                userPost.gCode = GuidHelper.GetGuid();
                                userPost.gUserCode = sysUser.gCode;
                                userPost.gPostCode = item;
                                tran.CommandSet<SysUserPostEntity>().Insert(userPost);
                            }

                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "操作成功";
                        }
                        else
                        {
                            resultInfo.Msg = $"账号{sysUser.sLoginName}已存在！";
                        }
                    });
                }
                else
                {
                    resultInfo.Msg = "两次输入密码不一致！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 编辑保存信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyInfo(UserModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            {
                var result = 0;
                //添加功能，直接添加
                con.Transaction(tran =>
                {
                    var userInfo = tran.QuerySet<SysUserEntity>().AndWhere(p => p.gCode == inputInfo.gCode)
                              .WithNoLock().Single();

                    userInfo.sUserName = inputInfo.sUserName;
                    userInfo.sPhone = inputInfo.sPhone;
                    userInfo.iSex = inputInfo.iSex;
                    userInfo.iState = inputInfo.iState;
                    userInfo.sPicUrl = inputInfo.sPicUrl;
                    result = tran.CommandSet<SysUserEntity>().Update(userInfo);

                    if (result > 0)
                    {
                        //先删除用户-角色关联信息
                        tran.CommandSet<SysUserRoleEntity>().AndWhere(p => p.gUserCode == userInfo.gCode).Delete();

                        //插入用户-角色关联信息
                        List<string> sRoleList = inputInfo.sRoleList.Split(',').ToList();
                        SysUserRoleEntity sysUserRole = null;
                        foreach (var item in sRoleList)
                        {
                            sysUserRole = new SysUserRoleEntity();
                            sysUserRole.gCode = GuidHelper.GetGuid();
                            sysUserRole.gUserCode = userInfo.gCode;
                            sysUserRole.gRoleCode = item;
                            tran.CommandSet<SysUserRoleEntity>().Insert(sysUserRole);
                        }

                        //先删除部门-角色关联信息
                        tran.CommandSet<SysUserDepartmentEntity>().AndWhere(p => p.gUserCode == userInfo.gCode).Delete();

                        //插入部门-角色关联信息
                        List<string> sDepartmentList = inputInfo.sDepartmentList.Split(',').ToList();
                        SysUserDepartmentEntity userDepartment = null;
                        foreach (var item in sDepartmentList)
                        {
                            userDepartment = new SysUserDepartmentEntity();
                            userDepartment.gCode = GuidHelper.GetGuid();
                            userDepartment.gUserCode = userInfo.gCode;
                            userDepartment.gDepartmentCode = item;
                            tran.CommandSet<SysUserDepartmentEntity>().Insert(userDepartment);
                        }

                        //先删除部门-角色关联信息
                        tran.CommandSet<SysUserPostEntity>().AndWhere(p => p.gUserCode == userInfo.gCode).Delete();

                        //插入岗位-角色关联信息
                        List<string> sPostList = inputInfo.sPostList.Split(',').ToList();
                        SysUserPostEntity userPost = null;
                        foreach (var item in sPostList)
                        {
                            userPost = new SysUserPostEntity();
                            userPost.gCode = GuidHelper.GetGuid();
                            userPost.gUserCode = userInfo.gCode;
                            userPost.gPostCode = item;
                            tran.CommandSet<SysUserPostEntity>().Insert(userPost);
                        }

                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功";
                    }
                    else
                    {
                        resultInfo.Msg = $"账号{userInfo.sLoginName}修改失败！";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;
                if (gCodeList.Count >= 0)
                {
                    result = con.CommandSql<int>().BySql(DataCommandManager.GetSQLCommand("BatchRemoveUsers", "SysUser"),
                          new
                          {
                              gCodeList = gCodeList

                          }).ExecuteNoQuery();

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "操作成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Msg = "ID为空，操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion
    }
}
